package com.open.capacity.forum.util;

import com.open.capacity.forum.dto.CommentDto;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang.StringUtils;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author moonholder
 * @Description 公共函数
 * @Date 19:34 2021/3/9
 */
public class Commons {
    /**
     * 显示文章内容，转换markdown为HTML
     *
     * @param markdown markdown文本
     * @return HTML文本
     */
    public static String mdToHtml(String markdown) {
        if (StringUtils.isNotBlank(markdown)) {
            markdown = markdown.replace("<!--more-->", "\r\n");
            markdown = markdown.replace("<!-- more -->", "\r\n");
            java.util.List<Extension> extensions = Collections.singletonList(TablesExtension.create());
            org.commonmark.parser.Parser parser = org.commonmark.parser.Parser.builder().extensions(extensions).build();
            Node document = parser.parse(markdown);
            HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
            String content = renderer.render(document);
            content = EmojiParser.parseToUnicode(content);
            return content;
        }
        return "";
    }


    /**
     * 填充子级评论
     *
     * @param commentList 评论集合
     * @return
     */
    public static List<CommentDto> fillCommentChildren(List<CommentDto> commentList) {
        List<CommentDto> result = new ArrayList<>();
        for (CommentDto comment : commentList) {
            if (comment.getPcomid() == null || comment.getPcomid() == 0L) {
                result.add(findChildren(comment,commentList));
            }
        }
        return result;
    }

    private static CommentDto findChildren(CommentDto item, List<CommentDto> protoList) {
        return item.setChildren(getCommentChild(item, protoList));
    }

    private static List<CommentDto> getCommentChild(CommentDto parentItem,List<CommentDto> protoList) {
        List<CommentDto> childList = new ArrayList<>();
        for (CommentDto item : protoList) {
            Long parentId = item.getPcomid();
            if (parentId != null && parentId.equals(parentItem.getComtid())) {
                childList.add(item);
            }
        }
        return childList;
    }

}
